<template>
	<view class="content">
		<o-navbarx :back="true" title="提交订单" :isback="false" color="#000000" background="linear-gradient( 92deg, #DAF1E7 0%, #DAF1E7 28%, #DAF1E7 38%, #D4EBE1 50%, #CDE7DC 62%, #D0E9DF 76%, #DAF1E7 100%);">
		</o-navbarx>
		<view class="index_bg_top pad-lr-20 mar-top-20">
			<view class="radius-16 bgfff pad-lr-20 pad-tb-30 mar-top-20" v-if="pageinfo?.buy_type==1&&merchant?.id">
				<view class=" display-sb align-items">
					<view class="fontSize-30 display align-items">{{merchant?.name}} <image src="/static/img/icon_dianhua.png" class="ml20 proudct-item-icon-24"></image></view>
					<view class="display align-items fontSize-26 col-2DB295 width150" @click="gopickup"><text>切换</text><image src="/static/img/icon_youjiantou_.png" class="wid-hig-28 ml10"></image></view>					
				</view>
				<view class="display align-items mar-top-20">
					<image src="/static/img/icon_juli.png" class="proudct-item-icon-15" mode=""></image>
					<view class="ml10 col-6 fontSize-26">距离{{merchant?.distance}}km</view>
				</view>
			</view>
			<view class="radius-16 bgfff pad-lr-20 pad-tb-30 mar-top-20" v-if="pageinfo?.buy_type==1&&!merchant?.id">
				<view class=" display-sb align-items" @click="gopickup">
					<view class="display-ce align-items">
						<view class="ml20 fontSize-30">选择自提点</view>
					</view>
					<view class="display align-items fontSize-26 col-2DB295" @click="gopickup"><image src="/static/img/icon_youjiantou_.png" class="wid-hig-28 ml10"></image></view>					
				</view>
			</view>
			<view class="radius-16 bgfff pad-lr-20 pad-tb-30 mar-top-20" v-if="pageinfo?.buy_type==2&&pageinfo?.address_info?.id>0">
				<view class=" display-sb align-items">
					<view class="fontSize-30">
						<view class="">{{pageinfo?.address_info?.name}}   {{pageinfo?.address_info?.mobile}}</view> 
						<view class="display align-items mar-top-20">
							<text class="col-f text-align-center pad-lr-12 pad-tb-4 fontSize-22 radius-4 tags_view" v-if="pageinfo?.address_info?.is_default==1">默认</text>
							<text class="ml10 fontSize-28 col-6">{{pageinfo?.address_info?.province}}{{pageinfo?.address_info?.city}}{{pageinfo?.address_info?.area}}{{pageinfo?.address_info?.detail}}</text>
						</view>
					</view>
					<view class="display align-items fontSize-26 col-2DB295" @click="goaddresslist"><image src="/static/img/icon_youjiantou_.png" class="wid-hig-28 ml10"></image></view>					
				</view>
			</view>
			<view class="radius-16 bgfff pad-lr-20 pad-tb-30 mar-top-20" v-if="pageinfo?.buy_type==2&&!pageinfo?.address_info?.id">
				<view class=" display-sb align-items" @click="goaddresslist">
					<view class="display-ce align-items width-80">
						<image src="/static/img/icon_tianjiadizhi.png" class="proudct-item-icon-26 ml60" mode=""></image>
						<view class="ml20 fontSize-30">点击添加地址</view>
					</view>
					<view class="display align-items fontSize-26 col-2DB295" @click="goaddresslist"><image src="/static/img/icon_youjiantou_.png" class="wid-hig-28 ml10"></image></view>					
				</view>
			</view>
			<view class="mar-top-20 pad-lr-20 pad-tb-20 radius-16 bgfff display align-items" v-for="item in pageinfo?.val" :key="item.attr_name">
				<image :src="item.cover" class="proudct-item-icon-10 radius-16" mode=""></image>
				<view class="ml20 right_width">
					<view class="text-clamp-1 fontSize-28">{{item.name}}</view>
					<view class="display-sb align-items mar-top-20 fontSize-26 col-6">
						<text>{{item.attr_name}}</text><text>x{{item.num}}</text>
					</view>
					<view class="mar-top-22 fontSize-28 col-E23737"><text class="fontSize-20">￥</text>{{item.price}}</view>
				</view>
			</view>
			<view class="mar-top-20 pad-lr-20 pad-tb-20 radius-16 bgfff">
				<view class="fontSize-28">价格明细</view>
				<view class="pad-tb-30 display-sb align-items border_bottom_F1 fontSize-26">
					<text>商品金额</text><text>￥{{pageinfo?.all_price}}</text>
				</view>
				<view class="pad-tb-30 display-sb align-items border_bottom_F1 fontSize-26" v-if="pageinfo?.buy_type==2">
					<text>运费</text><text>￥{{freight_money}}</text>
				</view>
				<view class="pad-tb-30 display-sb align-items fontSize-26">
					<text>订单金额</text><text>￥{{pageinfo?.order_price}}</text>
				</view>
			</view>
			<view class="mar-top-20 radius-16 pad-tb-30 pad-lr-20 bgfff display-sb align-items">
				<view class="display align-items">
					<image src="/static/img/icon_jifenzhifu.png" class="proudct-item-icon-24" mode=""></image>
					<view class="fontSize-28 ml20">积分支付</view>
					<view class="ml20 fontSize-26 col-6">{{pageinfo?.user_score}}积分可用</view>
				</view>
				<view class="fontSize-28 col-F6911B">-￥{{pageinfo?.dis_money}}</view>
			</view>
		</view>
		<view class="poFi bottom-0 width-100 bgfff">
			<view class="pad-lr-20 display-sb align-items bottom_view">
				<view class="">
					<view class="fontSize-24 col-F6911B">积分已抵扣￥{{pageinfo?.dis_money}}</view>
					<view class="fontSize-26 mar-top-4">还需支付：<text class="fontSize-30 col-E23737">￥{{pageinfo?.need_pay_price}}</text></view>
				</view>
				<view class=" display align-items">
					<view class="col-f fontSize-32 text-align-center pad-tb-16 radius-40 ml20 add_car" @click="gopaysuccess">支付</view>
				</view>
			</view>
		</view>
		<tm-overlay v-model:show="richshow" contentAnimation>
			<view @click.stop="" class="bgfff radius-16 pad-lr-30 pad-tb-30 width-80" style="height: 600rpx;overflow-y: scroll;">
				<view class="">{{richshowtxt}}</view>
			</view>
		</tm-overlay>
		<o-paypass ref="yspay" @submit="submitpay"></o-paypass>
	</view>
</template>

<script lang="ts" setup>
import { onLoad, onShow, onUnload } from '@dcloudio/uni-app';
import {getsettlePage,subOrder,payOrder} from '@/utils/api'
import { ref } from 'vue';

// 声明微信支付相关类型
declare const WeixinJSBridge: any;
declare const wx: any;
onLoad((options: any)=>{
	if(options.obj){
		Obj.value = JSON.parse(options.obj)
	}
	if(options.ids){
		cart_ids.value = options.ids
	}
	type.value = options.type
	_now_buy(2)
	
})
onShow(()=>{
uni.$on('selectshop',(e)=>{
		merchant.value = e
	})
	uni.$on('selectaddress',(e)=>{
		pageinfo.value.address_info = e
		refreshSettleData()
	})
})
onUnload(()=>{
	uni.$off('selectshop')
	uni.$off('selectaddress')
})
const richshow = ref(false)
const richshowtxt = ref()
const cart_ids = ref()//购物车下单，购物车ids
const type = ref()//提交,1直接购买,2购物车提交
const Obj = ref({
	goods_id:'',//商品ID type为1必填
	attr_id:'',//商品规格列表ID type为1必填
	num:''//商品数量 type为1必填
})
const merchant = ref()//字体点信息
//页面展示数据
const pageinfo = ref()//页面数据
const freight_money = ref(0)//运费
const _now_buy =(typex:number|string) =>{
	// 构建请求参数
	let params: any = {}
	
	if(type.value == 1){
		// 直接购买
		params = {
			goods_id: Obj.value.goods_id,
			attr_id: Obj.value.attr_id,
			num: Obj.value.num,
			merchant_id: merchant.value?.id || '',
			address_id: pageinfo.value?.address_info?.id || ''
		}
	}else{
		// 购物车购买
		params = {
			ids: cart_ids.value,
			merchant_id: merchant.value?.id || '',
			address_id: pageinfo.value?.address_info?.id || ''
		}
	}
	
	// 调用真实接口
	getsettlePage(params).then((res: any) => {
		if(res.code == 1){
			if(typex!=1){
				pageinfo.value = res.data
			}else{
				pageinfo.value.need_pay_price = res.data.need_pay_price
			}
		}else{
			uni.showToast({
				title: res.msg || '获取订单信息失败',
				icon: 'none'
			})
		}
	}).catch((err: any) => {
		console.error('获取订单信息失败:', err)
		uni.showToast({
			title: '网络错误，请重试',
			icon: 'none'
		})
	})
}
// 重新获取结算数据（当地址或自提点改变时）
const refreshSettleData = () => {
	_now_buy(2)
}
const gopickup =() =>{
	uni.navigateTo({
		url:'/indexpages/pickup/pickup?info='+(JSON.stringify(merchant.value)||'')
	})
}
const gopaysuccess =() =>{
	let ObjData
	if(type.value==1&&pageinfo.value.buy_type==1){
		 ObjData = {
			goods_id:Obj.value.goods_id,
			attr_id:Obj.value.attr_id,
			number:Obj.value.num,
			merchant_id:merchant.value?.id,
			original_price:pageinfo.value.all_price,
			pay_price:pageinfo.value.order_price,
			use_score:pageinfo.value.dis_score,
			score_money:pageinfo.value.dis_money,
			remarks:'',
			type:1,
			freight:freight_money.value
		}
	}else if(type.value==2&&pageinfo.value.buy_type==1){
		let list:any = []
		pageinfo.value.val.forEach((item: any)=>{
			list.push({cart_id:item.id,merchant_id:merchant.value?.id||'',number:item.num})
		})
		ObjData = {
			goods_list:list,
			original_price:pageinfo.value.all_price,
			pay_price:pageinfo.value.order_price,
			use_score:pageinfo.value.dis_score,
			score_money:pageinfo.value.dis_money,
			remarks:'',
			type:2,
			freight:freight_money.value
		}
	}else if(type.value==1&&pageinfo.value.buy_type==2){
		ObjData = {
			goods_id:Obj.value.goods_id,
			attr_id:Obj.value.attr_id,
			number:Obj.value.num,
			address_id:pageinfo.value?.address_info?.id,
			original_price:pageinfo.value.all_price,
			pay_price:pageinfo.value.order_price,
			use_score:pageinfo.value.dis_score,
			score_money:pageinfo.value.dis_money,
			remarks:'',
			type:1,
			freight:freight_money.value
		}
	}else if(type.value==2&&pageinfo.value.buy_type==2){
		let list:any = []
		pageinfo.value.val.forEach((item: any)=>{
			list.push({cart_id:item.id,attr_id:item.attr_id,number:item.num})
		})
		ObjData = {
			goods_list:list,
			original_price:pageinfo.value.all_price,
			pay_price:pageinfo.value.order_price,
			use_score:pageinfo.value.dis_score,
			score_money:pageinfo.value.dis_money,
			address_id:pageinfo.value?.address_info?.id,
			remarks:'',
			type:2,
			freight:freight_money.value
		}
	}
	// 调用真实提交订单接口
	subOrder(ObjData).then((res: any) => {
		if(res.code == 1){
			order_id.value = res.data.order_id
			pay(res.data.order_code, res.data.buy_type, res.data.use_score)
		}else{
			uni.showToast({
				title: res.msg || '提交订单失败',
				icon: 'none'
			})
		}
	}).catch((err: any) => {
		console.error('提交订单失败:', err)
		uni.showToast({
			title: '网络错误，请重试',
			icon: 'none'
		})
	})
}
const yspay = ref()
const pay = (order_code:string,buy_type:string|number,use_score:string|number) =>{
	if(use_score==1){
		buy_typex.value = buy_type
		order_codex.value = order_code
		// yspay.value.show();//需要密码支付打开
		uni.showModal({
			title: '提示',
			content: '确认扣除积分?',
			success: function (res) {
				if (res.confirm) {
					submitpay({value:'1'})
				} else if (res.cancel) {
					uni.redirectTo({
						url:'/mypages/orderlist/orderlist?state=0'
					})
				}
			}
		});
	}else{
		wxpay(order_code,buy_type,'')
	}
}
const order_codex = ref(),
	  order_id = ref(),
	  buy_typex = ref();
const submitpay =(e: any) =>{
	wxpay(order_codex.value,buy_typex.value,e.value)
}
const wxpay =(order_code:string,buy_type:string|number,pay_password:string) =>{
	// 调用真实支付接口
	payOrder({
		order_code: order_code,
		pay_password: pay_password
	}).then((res: any) => {
		if(res.code==1){
			// 检查是否有支付数据
			if (!res.data) {
				uni.showToast({
					title: '支付数据获取失败',
					icon: 'none'
				});
				return;
			}
			// 微信公众号支付 - 使用 EasyWeChat
			console.log('EasyWeChat 支付参数:', res.data);
			
			// 检查支付参数是否完整
			if (!res.data || !res.data.appId || !res.data.timeStamp) {
				uni.showToast({
					title: '支付参数错误',
					icon: 'none'
				});
				return;
			}
			
			// 调用微信支付
			callWechatPay(res.data);
		}else if(res.code==555){
			// 积分支付
			uni.showModal({
				title: '提示',
				content: '确认扣除积分?',
				success: function (res) {
					if (res.confirm) {
						submitpay({value:'1'})
					} else if (res.cancel) {
						uni.redirectTo({
							url:'/mypages/orderlist/orderlist?state=0'
						})
					}
				}
			});
			
		}else{
			uni.showToast({
				icon: 'none',
				title: res.msg || '支付失败'
			})
		}
	}).catch((err: any) => {
		console.error('支付接口调用失败:', err)
		uni.showToast({
			title: '网络错误，请重试',
			icon: 'none'
		})
	})
}
// 调用微信支付
const callWechatPay = (payData: any) => {
	console.log('开始调用微信支付:', payData);
	console.log('WeixinJSBridge 存在:', typeof WeixinJSBridge !== 'undefined');
	console.log('wx 存在:', typeof wx !== 'undefined');
	
	// 等待微信环境加载完成
	const tryWechatPay = () => {
		if (typeof WeixinJSBridge !== 'undefined') {
			console.log('使用 WeixinJSBridge 调用微信支付');
			// 使用WeixinJSBridge调用微信支付
			WeixinJSBridge.invoke('getBrandWCPayRequest', {
				appId: payData.appId,
				timeStamp: payData.timeStamp,
				nonceStr: payData.nonceStr,
				package: payData.package,
				signType: payData.signType,
				paySign: payData.paySign
			}, (result: any) => {
				console.log('WeixinJSBridge 支付结果:', result);
				handlePayResult(result);
			});
		} else if (typeof wx !== 'undefined') {
			console.log('使用 wx.chooseWXPay 调用微信支付');
			// 使用微信JS-SDK的支付接口
			wx.chooseWXPay({
				timestamp: payData.timeStamp,
				nonceStr: payData.nonceStr,
				package: payData.package,
				signType: payData.signType,
				paySign: payData.paySign,
				success: (result: any) => {
					console.log('wx.chooseWXPay 支付成功:', result);
					handlePayResult({err_msg: 'get_brand_wcpay_request:ok'});
				},
				cancel: (result: any) => {
					console.log('wx.chooseWXPay 支付取消:', result);
					handlePayResult({err_msg: 'get_brand_wcpay_request:cancel'});
				},
				fail: (result: any) => {
					console.log('wx.chooseWXPay 支付失败:', result);
					handlePayResult({err_msg: 'get_brand_wcpay_request:fail'});
				}
			});
		} else {
			console.log('微信支付环境检查失败，等待加载...');
			// 如果微信环境还没加载完成，等待一下再试
			setTimeout(() => {
				if (typeof WeixinJSBridge !== 'undefined' || typeof wx !== 'undefined') {
					tryWechatPay();
				} else {
					uni.showToast({
						title: '请在微信中打开',
						icon: 'none'
					});
				}
			}, 1000);
		}
	};
	
	tryWechatPay();
}

// 处理支付结果
const handlePayResult = (result: any) => {
	if (result.err_msg === 'get_brand_wcpay_request:ok') {
		uni.showToast({
			icon: 'none',
			title: '支付成功！'
		})
		uni.redirectTo({
			url:'/indexpages/paysuccess/paysuccess?type='+pageinfo.value.buy_type+'&order_id='+order_id.value
		})
	} else if (result.err_msg === 'get_brand_wcpay_request:cancel') {
		uni.showToast({
			icon: 'none',
			title: '已取消支付！'
		})
	} else {
		uni.showToast({
			icon: 'none',
			title: '支付失败！'
		})
	}
}

const goaddresslist =() =>{
	uni.navigateTo({
		url:'/indexpages/addresslist/addresslist'
	})
}
</script>

<style lang="scss">
@import 'setorder.scss';
</style>
